#TODO: one window per name
#TODO: add buddy
#TODO: presence setting
#TODO: real login
#TODO: publish !

class ChatController < ApplicationController
  
  layout "login"
  
  def index
  end
  
  def login
    begin
      session['login'] = "protaskm@gmail.com" # TODO: config
      MiddleMan.new_worker(:worker => :xmpp_worker, :job_key => session['login'])
      MiddleMan.ask_work(:worker => :xmpp_worker, :job_key => session['login'], :worker_method => :login, :data => session['login'])
      @roster = Roster.find(:all, :conditions => "owner_jid = '#{session['login']}'", :order=>"prestype,alias,jid")
      render(:partial=>'chat_window')
    rescue Exception => e
      render(:text => "Error. #{e.message}. Is backgroundrb running ?", :status => 500)
    end
  end
  
  def set_presence
    MiddleMan.ask_work(:worker => :xmpp_worker, :job_key => session['login'], :worker_method => :set_presence, :data => "I am PTM's robot. http://protaskm.com")
    refresh_roster
  end
  
  def refresh_roster
    @roster = Roster.find(:all, :conditions => "owner_jid = '#{session['login']}'", :order=>"prestype,alias,jid")
    render(:partial=>'roster', :collection => @roster)
  end
  
  def refresh_msgs
    @to = params[:to]
    @msgs = Chatmsgs.find(:all,:conditions=>"(owner_jid='#{session['login']}' and jid='#{@to}') or (jid='#{session['login']}' and owner_jid='#{@to}')", :order=>"created_on")
    to_r = Roster.find(:first,:conditions=>{:jid=>@to})
    to_r.update_attribute(:has_sent_msg,0) if to_r
    render(:partial=>'msg', :collection=>@msgs)    
  end
  
  def send_msg
    to  = params[:to]
    msg = params[:msg]
    MiddleMan.ask_work(:worker => :xmpp_worker, :job_key => session['login'], :worker_method => :send_msg, :data => {:to=>to, :msg=>msg})
    render(:text=>'msg sent')
  end
  
  #def ping
  #  MiddleMan.ask_work(:worker => :xmpp_worker, :worker_method => :ping)    
  #end
  
  def show_msg
    @to = params[:to]
    @msgs = Chatmsgs.find(:all,:conditions=>"(owner_jid='#{session['login']}' and jid='#{@to}') or (jid='#{session['login']}' and owner_jid='#{@to}')", :order=>"created_on")
    #@msgs.each {|msg| msg.update_attribute(:readstatus,1)}
    to_r = Roster.find(:first,:conditions=>{:jid=>@to})
    to_r.update_attribute(:has_sent_msg,0) if to_r
    render(:partial=>"msg_window", :layout => 'notes')
  end
  
  def log_out
    MiddleMan.ask_work(:worker => :xmpp_worker, :job_key => session['login'], :worker_method => :log_out)
    render(:action => 'index')
  end
  
end
